<?php
namespace app\backend\controller;

class Backend {
	
	protected $manager_id;
	
	/**
	 * 构造函数
	 * 加载后优先执行
	 */
	public function __construct() {
		
		$this->manager_id = \think\Session::get('manager_id');
		if(false == $this->manager_id){
			var_dump('登录失效');
			exit();
		};
		
	}
	
	/**
	 * 处理Json数据
	 * 处理按规定格式返回的数据
	 */
	protected function disposeJson($error_number, $error_message, $suffix_array = null) {
		
		$array = array(
			'errno' => $error_number,
			'message' => $error_message,
		);
		
		if(null !== $suffix_array){
			$array['data'] = $suffix_array;
		};
		
		return $array;
	}
	
	/**
	 * 初始化Redis
	 */
	protected function getRedis() {
		
		if(!class_exists('Redis')){
			$this->returnError(9, '当前不支持Redis');
		};
		
		\think\Config::load(CONF_PATH . 'redis.php');
		$redis_service = \think\Config::get('redis_service');
		if(!is_array($redis_service)){
			$this->returnError(9, '当前Redis配置参数有误，请联系管理员');
		};
		
		$redis = new \Redis();
		if(is_integer($redis_service['port'])){
			$result = $redis->connect($redis_service['host'], $redis_service['port']);
		}else{
			$result = $redis->connect($redis_service['host']);
		};
		if(true !== $result){
			$this->returnError(9, '连接Redis服务失败，请联系管理员');
		};
		
		if(is_string($redis_service['auth'])){
			$result = $redis->auth($redis_service['auth']);
			if(true !== $result){
				$this->returnError(9, '认证Redis服务失败，请联系管理员');
			};
		};
		
		if(is_integer($redis_service['select'])){
			$result = $redis->select($redis_service['select']);
			if(true !== $result){
				$this->returnError(9, '选择Redis服务库失败，请联系管理员');
			};
		};
		
		return $redis;
	}
	
	/**
	 * 处理并返回Html信息
	 */
	protected function disposeHtml($message, $view) {
		
		$result = array(
			'message' => $message,
		);
		
		return $view->fetch(\think\Config::get('templete_error'), $result);
	}
	
	/**
	 * 返回错误信息
	 * 跳过框架的返回机制，判断请求类型，直接返回Html或Ajax
	 */
	protected function returnError($message, $header = array()) {
		
        $result = [
            'errno' => 9,
            'message'  => $message,
        ];

		$isAjax = \think\Request::instance()->isAjax();
        $type =  $isAjax ? \think\Config::get('default_ajax_return') : \think\Config::get('default_return_type');
        if('html' == strtolower($type)){
            $result = \think\View::instance()
                ->fetch(\think\Config::get('templete_error'), $result);
        };
        $response = \think\Response::create($result, $type)->header($header);
        throw new \think\exception\HttpResponseException($response);
	}
	
}